package com.axend.aerosense.common.connect.tcp;

import com.axend.aerosense.base.utils.ByteUtils;
import com.axend.aerosense.base.utils.Values;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * 雷达通信命令
 * @author ChenHongWei
 * @date :2021/1/15 17:10
 */

public class RadarProvide {

    private TcpClient tcpClient;
    private static List<byte[]> byteArrList = new ArrayList<>();
    private boolean isSend = false;
    static {
        byteArrList.add(getIdByByte());  //获取雷达ID
        byteArrList.add(getWorkDistanceByByte());   //获取雷达工作距离
        byteArrList.add(getAlarmDelayByByte());  //获取雷达报警时间
        byteArrList.add(getDeviceHeightByByte());     //获取雷达安装高度
        byteArrList.add(getHardwareVersionByByte());      //获取雷达固件版本
    }

    public RadarProvide(TcpClient tcpClient) {
        this.tcpClient = tcpClient;
    }

    public void getDeviceData(){
        Thread thread = new Thread(){
            @Override
            public void run() {
                int current = 0;
                try {
                    while (interrupted()){
                        if (current == byteArrList.size()){
                            interrupt();
                            break;
                        }
                        tcpClient.writeData(byteArrList.get(current));
                        sleep(1000);
                        if (isSend) {
                            //如果发送成功，继续下发下一条命令
                            isSend = false;
                            current++;
                            continue;
                        } else {
                            for (int i = 0; i < 2; i++){
                                sleep(1000);
                                if (isSend){
                                    isSend = false;
                                    current++;
                                    continue;
                                }else {
                                    tcpClient.writeData(byteArrList.get(current));
                                }
                            }
                            //如果重试都失败，则放弃
                            isSend = false;
                            current++;
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }

    public void sendSuccess(){
        isSend = true;
    }

    /**
     * 获取雷达id命令
     */
    public void getId(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.GET_RID), ByteUtils.hexStringToBytes(Values.GET_DATA));
        tcpClient.writeData(data);
    }

    public static byte[] getIdByByte(){
        return mergeByte(ByteUtils.hexStringToBytes(Values.GET_RID), ByteUtils.hexStringToBytes(Values.GET_DATA));
    }

    /**
     * 转换雷达id
     * @param bytes
     * @return
     */
    public String getIdByStr(byte[] bytes){
        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 设置工作距离（米）
     * @param distance
     */
    public void setWorkDistance(float distance){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_WORK_DISTANCE), ByteUtils.floatToByte(distance));
        tcpClient.writeData(data);
    }

    /**
     * 获取工作距离
     */
    public void getWorkDistance(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.GET_WORK_DISTANCE), ByteUtils.hexStringToBytes(Values.GET_DATA));
        tcpClient.writeData(data);
    }

    public static byte[] getWorkDistanceByByte(){
        return mergeByte(ByteUtils.hexStringToBytes(Values.GET_WORK_DISTANCE), ByteUtils.hexStringToBytes(Values.GET_DATA));
    }

    /**
     * 转换工作距离
     */
    public float getWorkDistanceByFloat(byte[] bytes){
        return ByteUtils.byteToFloat(bytes, 0);
    }

    /**
     * 设置报警延时（秒）
     * @param delay
     */
    public void setAlarmDelay(int delay){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_WARING_DELAYED), ByteUtils.intToBytesLow2High(delay));
        tcpClient.writeData(data);
    }

    /**
     * 获取报警延时（秒）
     */
    public void getAlarmDelay(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.GET_WARING_DELAYED), ByteUtils.hexStringToBytes(Values.GET_DATA));
        tcpClient.writeData(data);
    }

    public static byte[] getAlarmDelayByByte(){
         return mergeByte(ByteUtils.hexStringToBytes(Values.GET_WARING_DELAYED), ByteUtils.hexStringToBytes(Values.GET_DATA));
    }

    /**
     * 转换报警延时
     * @param bytes
     * @return
     */
    public int getAlarmDelayByInt(byte[] bytes){
        return ByteUtils.byteToInt(bytes);
    }

    /**
     * 切换到STA模式
     */
    public void switchStaMode(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_COLLECT_GATE_STATE), ByteUtils.hexStringToBytes(Values.GET_DATA));
        tcpClient.writeData(data);
    }

    public byte[] getCheckStaMode(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_COLLECT_GATE_STATE), ByteUtils.hexStringToBytes(Values.GET_DATA));
        return data;
    }

    /**
     * 停止采集门位置
     */
//    public void stopSamplingGate(){
//        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_COLLECT_GATE_STATE), ByteUtils.hexStringToBytes(Values.SET_FAIL));
//        tcpClient.writeData(data);
//    }

    /**
     * 设置外出未回家报警延时
     */
    public void setNoGoHomeDelayed(int delayed){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_NO_GO_HOME_DELAYED), ByteUtils.intToBytesLow2High(delayed));
        tcpClient.writeData(data);
    }

    /**
     * 获取外出未回家报警延时
     */
    public void getNoGoHomeDelayed(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.GET_NO_GO_HOME_DELAYED), ByteUtils.hexStringToBytes(Values.GET_DATA));
        tcpClient.writeData(data);
    }

    /**
     * 转换获取外出未回家报警延时
     */
    public int getNoGoHomeDelayedByInt(byte[] bytes){
        return ByteUtils.byteToInt(bytes);
    }

    /**
     * 设置家庭wifi信息
     * @param ssid
     * @param password
     */
    public void setFamilyWifiInfo(String ssid, String password){
        byte[] bytes = (ssid + "," + password).getBytes();
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_WIFI_INFO), ByteUtils.inversionArr(bytes));
        tcpClient.writeData(data);
    }

    /**
     * 设置设备安装高度
     * @param heightType
     */
    public void setDeviceHeight(HeightType heightType){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.SET_DEVICE_HEIGHT), heightType.getBytes());
        tcpClient.writeData(data);
    }

    /**
     * 获取设备安装高度
     */
    public void getDeviceHeight(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.GET_DEVICE_HEIGHT), ByteUtils.hexStringToBytes(Values.GET_DATA));
        tcpClient.writeData(data);
    }

    public static byte[] getDeviceHeightByByte(){
         return mergeByte(ByteUtils.hexStringToBytes(Values.GET_DEVICE_HEIGHT), ByteUtils.hexStringToBytes(Values.GET_DATA));
    }

    /**
     * 转换设备安装高度
     */
    public HeightType getDeviceHeightByType(byte[] data){
        int type = ByteUtils.byteToInt(data);
        if (type == 0){
            return HeightType.HEIGHT_1_4;
        }else if (type == 1){
            return HeightType.HEIGHT_2_2;
        }else {
            try {
                throw new Throwable("没有此类型的安装高度！");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            return null;
        }
    }

    /**
     * 获取硬件版本
     */
    public void getHardwareVersion(){
        byte[] data = mergeByte(ByteUtils.hexStringToBytes(Values.GET_HARDWARE_VERSION), ByteUtils.hexStringToBytes(Values.GET_DATA));
        tcpClient.writeData(data);
    }

    public static byte[] getHardwareVersionByByte(){
         return mergeByte(ByteUtils.hexStringToBytes(Values.GET_HARDWARE_VERSION), ByteUtils.hexStringToBytes(Values.GET_DATA));
    }

    /**
     * 设置雷达IP地址与端口
     */
    public void setDeviceIPAndPort(){
        tcpClient.writeData(ByteUtils.hexStringToBytes("AAAA55551900000C6165726F73656E73652E61782D656E642E636F6D2C38303030"));
    }

    /**
     * 转换硬件版本到字符串
     */
//    public String getHardwareVersionByString(byte[] bytes){
//        byte[] data = ByteUtils.inversionArr(bytes);
//        ByteUtils.printHexString("myByte", bytes);
//        String str = "";
//        //将每个字节转换成Int
//        for (int i = 0; i < data.length; i++){
//            byte[] temp = {data[i]};
//            if (i == data.length -1){
//                str += Integer.parseInt(ByteUtils.bytesToHexString(temp), 16);
//            }else {
//                str += Integer.parseInt(ByteUtils.bytesToHexString(temp), 16) + ".";
//            }
//        }
//        return str;
//    }

    public String getHardwareVersionByString(byte[] bytes){
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(ByteUtils.inversionArr(bytes));
        buffer.rewind();
        String str = "";
        //将每个字节转换成Int
        for (int i = 0; i < 3; i++){
            byte b = buffer.get();
            byte[] temp = new byte[4];
            temp[3] = b;
            //如果是个位数前补零
            String hexString = String.format("%02d", ByteUtils.byteToInt(temp));
            if (i == bytes.length -2){
                str += hexString;
            }else {
                str += hexString + ".";
            }
        }
        return str;
    }

    //合并、转换命令
    public static byte[] mergeByte(byte[] tag, byte[] data){
        byte[] head = Values.HEAD_BYTE;
        byte[] lengthByte = ByteUtils.intToBytesHigh2Low(data.length);
        byte[] length = {lengthByte[0], lengthByte[1]};
        byte[] msg = ByteUtils.inversionArr(data);
        List<byte[]> list = new ArrayList<>();
        list.add(head);
        list.add(length);
        list.add(tag);
        list.add(msg);
        byte[] result = ByteUtils.mergeByteArray(list);
        return result;
    }

}
